package com.yifeng.repo.apm.endpoint.console.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yifeng.repo.apm.endpoint.console.api.LogConfService;
import com.yifeng.repo.apm.endpoint.console.api.model.LogConf;
import com.yifeng.repo.apm.endpoint.utils.BaseUtil;
import next.fire.spinus.logx.utils.env.HostManager;
import next.fire.spinus.logx.utils.http.HttpResult;

import java.util.Collections;
import java.util.List;

/**
 * Created by daibing on 2020/12/8
 */
public class LogConfServiceProxy extends CommonProxy implements LogConfService {
    private static final String SERVICE_MAPPING = "/rest/LogConfService";
    private final String serverUrl;

    public LogConfServiceProxy(String logConfUrl, String logAccessToken, int clientTimeoutMillis) {
        super(logConfUrl, logAccessToken, clientTimeoutMillis);
        this.serverUrl = buildServerUrl(logConfUrl);
    }

    @Override
    public List<LogConf> list(String appId, String appStage) {
        String url = serverUrl + "/" + "list";
        JSONObject params = new JSONObject();
        params.put("appId", appId);
        params.put("appStage", appStage);
        String json = params.toJSONString();
        HttpResult result = this.invoke(url, json, clientTimeoutMillis, logAccessToken);
        return result == null  ? Collections.emptyList() : JSON.parseArray(result.getResult(), LogConf.class);
    }

    private String buildServerUrl(String logConfUrl) {
        // 优先使用直接配置的服务context
        String serviceContext = HostManager.get().getEnvSetting("log.conf.server.context");
        if (BaseUtil.isNotBlank(serviceContext)) {
            return logConfUrl + serviceContext + SERVICE_MAPPING;
        }
        // 检查域名使用包含chief
        boolean isConnect2Spinus = logConfUrl.toLowerCase().contains("chief");
        if (isConnect2Spinus) {
            return logConfUrl + "/fire/fire-spinus" + SERVICE_MAPPING;
        }
        // 默认返回新项目的serverUrl
        return logConfUrl + "/yfcloud-apm/log" + SERVICE_MAPPING;
    }

}
